var questionDetail = new Object()
var options = [];


// 显示行业分类
function showBusinessType() {
    $("#varIndustryName").select2({
        tags: true,
        data: business_json,
        multiple: true,
        placeholder: "请选择行业",
        language: "zh-CN"
    });

    //$("#varIndustryName").val($("#varIndustry").val().split(',')).trigger("change");
}


// 保存
questionDetail.save = function save() {
    var feedbackId = $("#feedbackId").val();
    if (checkFormValue()) { //检查表单内容
        //  清空未填选项、
        $("#chooseOptions .row").each(function () {
            var obj = $(this);
            var textareaText = $(obj).find(" textarea").val();
            if (textareaText == "") {
                $(obj).html("");    //清除没内容的选项
            }
        });

        var form = $("#addQuestionForm");
        var options = {
            url: appPath + "/admin/questionSelf/save",
            success: function (datas) {
                if (datas.result == "error") {
                    layer.msg(datas.massagesg);
                    return;
                }
                if (feedbackId !== "") {
                    window.opener.feedback_self_list.initTable();
                }
                window.close();
            }
        }
        form.ajaxSubmit(options);
    }
};


// 检查表单内容
function checkFormValue() {
    //非空验证
    if ($("#title").val() == "") {
        layer.msg("试题内容不能为空");
        return false;
    }

    //设置varAnswer 的值
    var answer = "";
    allOptions();

    var radioVal = $("input[name='chrType']:checked").val();
    // 新增客观题以及填空题时，题目中必须要有（）
    if (radioVal == '01' || radioVal == '02' || radioVal == '03' || radioVal == '04') {
        var num = checkTianKongNum();
        if (num == 0) {
            layer.msg("题目中没有（），无法保存。");
            return false;
        }
    }

    //单选
    if (radioVal == '01') {
        if (optionsIsNull() == false) {
            layer.msg("选项内容不能为空！");
            return false;
        }
        var objValue = $("select[name='radioAnswer']").val();
        if ($.inArray(objValue, options) > -1) {
            answer = objValue; //单选正确答案
        } else {
            layer.msg(objValue + "选项内容为空！");
            return false;
        }


    }
    //多选
    if (radioVal == '02') {
        if (optionsIsNull() == false) {
            layer.msg("选项内容不能为空！");
            return false;
        }
        var checks = $("input[name='checkBoxAnswer']:checked");
        var flag = true;
        $(checks).each(function () {//多选正确答案
            var objValue = $(this).val();
            if ($.inArray(objValue, options) > -1) {
                answer += objValue;
            } else {
                layer.msg(objValue + "选项内容为空！");
                flag = false;
                return flag;
            }
        });
        if (flag) {
            if ("" == answer || answer.length == 1) {
                layer.msg("多选题答案需2个及以上!");
                return false;
            }

        } else {
            return false;
        }

    }

    //判断
    if (radioVal == '03') {
        answer = $("select[name='checkAnswer']").val()  //判断题正确答案
    }


    // 单选+多选+判断
    if (radioVal == '01' || radioVal == '02' || radioVal == '03') {
        if (answer == "") {
            layer.msg("正确答案不能为空");
            return false;
        } else {
            $("#varAnswer").val(answer);
        }
    }

    // 填空题
    if (radioVal == '04') {
        // 填空题答案拼接
        var varAnswerDesc = "";

        // 第几个参考答案为空
        var varAnswerIfNull = "";

        //判断题正确答案
        var tianKongNum = parseInt($("#tianKongHidden").val());
        for (var i = 1; i <= tianKongNum; i++) {

            var tianKongAnswerNull = $("#tianKongAnswer" + i).val();
            if (tianKongAnswerNull == "") {
                varAnswerIfNull = i;
                break;
            }

            if (i == tianKongNum) {
                varAnswerDesc += "{" + $("#tianKongAnswer" + i).val() + "}";
            } else {
                varAnswerDesc += "{" + $("#tianKongAnswer" + i).val() + "},";
            }
        }

        // 校验填空个数和参考答案个数不一致
        var num = checkTianKongNum();
        if (num != tianKongNum) {
            layer.msg("空的数量与答案数量不一致，请检查修改");
            return false;
        }


        // 校验单个答案不能为空
        if (varAnswerIfNull != "") {
            layer.msg("空 " + varAnswerIfNull + " 参考答案不能为空");
            return false;
        }

        $("#varAnswerDesc").val(varAnswerDesc);
    }


    if (radioVal == '03') {
        $("#chooseOptions").html("");
    } else {
        $("#checkOptions").html("");
    }

    // 简答+论述
    if (radioVal == '05' || radioVal == '06' || radioVal == '07' || radioVal == '08') {
        var varAnswerDesc = $("#textAreaAnswerDesc").val()  //简答+论述正确答案
        if (varAnswerDesc == "") {
            layer.msg("参考答案不能为空");
            return false;
        }
        $("#varAnswerDesc").val(varAnswerDesc);
    }

    return true;
}

// 校验填空个数和参考答案个数不一致（最多支持五个空格）
function checkTianKongNum() {

    // 题目内容
    var title = $("#title").val();

    // 正则表达式
    var reg = /[\(|（]([^\(\)（）]*)[\)|）]/ig;

    var t = title.match(reg);
    if (t == null) {
        return 0;
    }

    // 总共括号个数
    var num = title.match(reg).length;

    return num;

}

// 填空参考答案 增加删除一项 最多支持四项
function tianKongAddOrDel(funcName){

    var tianKongNum = $("#tianKongHidden").val();
    tianKongNum = parseInt(tianKongNum);

    //添加一项
    if(funcName == 'add'){
        tianKongNum += 1;
        $("#delTianKong").show();
        $("#tianKongAnswerDiv" + tianKongNum).show();

        $("#tianKongHidden").val(tianKongNum)
    }
    //删除一项
    else{
        $("#addTianKong").show();
        $("#tianKongAnswerDiv" + tianKongNum).hide();
        // 删除项中的值置为空
        $("#tianKongAnswer" + tianKongNum).val("");

        tianKongNum -= 1;
        $("#tianKongHidden").val(tianKongNum)
    }

    if (tianKongNum == 1) {
        $("#delTianKong").hide();
    }

    if (tianKongNum == 4) {
        $("#addTianKong").hide();
    }
}

// 单选多选选项内容是否为空
function optionsIsNull() {
    var result = true;
    $("#chooseOptions .row").each(function () {
        var obj = $(this);
        var objOption = $(obj).attr("opName");
        var textareaText = $(obj).find(" textarea").val();
        if (objOption == 'A' || objOption == 'B' || objOption == 'C') {
            if (textareaText == "") {
                result = false;
            }
        }
    });
    return result;
}


//清空未填选项
function allOptions() {
    $("#chooseOptions .row").each(function () {
        var obj = $(this);
        var objOption = $(obj).attr("opName");
        var textareaText = $(obj).find(" textarea").val();
        if (textareaText != "") {
            options.push(objOption);//记录有内容的选项
        }
    });
}


// 渲染图片
function imageHtml(images, imageLable, update) {

    var arr = [];

    arr = images.split(";");
    var html = "";
    for (var i = 0; i < arr.length; i++) {

        var sing = arr[i].split(",");

        // 修改的时候，能够删除图片
        if (update == '1') {

            // html += '<lable id=\'' + sing[0].split(".")[0] + '\'><span>' + sing[1] + '</span>' + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a style="color: #0e90d2" onclick="delLable(\''+sing[0].split(".")[0]+'\',\''+ imageLable +'\')" >' + '删除' + "</a></br></lable>";

            html += '<label id="' + sing[0].split(".")[0] + '">';
            html += '<span>' + sing[1] + '</span>&nbsp;&nbsp;';
            html += '<a style="color: #0e90d2" href="' + appPath + '/popup/msg/download/' + sing[0] + '?fileName=' + sing[1] + '">下载</a>&nbsp;&nbsp;';
            html += '<a style="color: #0e90d2" onclick="delLable(\'' + sing[0].split(".")[0] + '\',\'' + imageLable + '\',\'' + arr + '\')">删除</a>';
            html += '</br>';
            html += '</label>&nbsp;&nbsp;&nbsp;';


            // 试题解析不能修改
        } else {
            // html += '<lable id=\'' + sing[0].split(".")[0] + '\'><span>' + sing[1] + '</span>' + '&nbsp;' + "</br></lable>";

            html += '<label id="' + sing[0].split(".")[0] + '">';
            html += '<span>' + sing[1] + '</span>&nbsp;&nbsp;';
            html += '<a style="color: #0e90d2" href="' + appPath + '/popup/msg/download/' + sing[0] + '?fileName=' + sing[1] + '">下载</a>&nbsp;&nbsp;';
            // html += '<a style="color: #0e90d2" onclick="delLable(\''+ sing[0].split(".")[0] +'\',\''+ imageLable +'\')">删除</a>';
            html += '</br>';
            html += '</label>&nbsp;&nbsp;&nbsp;';


        }
    }
    $("#" + imageLable).html(html);
}

// *************************图片上传功能************************

// 点击上传图片  弹出图片上传模态框
function uploadImage(lableId) {

    // 记录当前上传图片的地方
    $("#imageLable").val(lableId);

    //$("#attachmentUploadDialog").modal("show");
    $("#fileList").val("");

    layer.open({
        type: 2,
        title: '上传附件',
        area: ['1000px', '400px'],		//弹出层大小
        scrollbar: false,				//false隐藏滑动块
        btn: ['保存', '取消'],
        content: [appPath + '/admin/questionSelf/upload?ifImg=1', 'yes'],
        btn1: function (index, layero) {
            layer.close(index);
            var fileList = layero.find("iframe")[0].contentWindow.$("#fileList").val();
            saveImg(fileList);
        },
        btn2: function (index) {
            layer.close(index);
        }
    });
}


function saveImg(fileList) {

    if ("" == fileList) {
        layer.msg("请先上传图片后保存！", {icon: 7});
        return;
    }

    var arr = [];

    // 点击的是哪个地方的按钮
    var imageLable = $("#imageLable").val();

    // 选项图片最多只能一张
    if (imageLable == 'itemALable' || imageLable == 'itemBLable' || imageLable == 'itemCLable'
        || imageLable == 'itemDLable' || imageLable == 'itemELable' || imageLable == 'itemFLable') {

        var lableImages = fileList;
        arr = lableImages.split(";");
        // 就用第一张图片
        $("#" + imageLable + "Images").val(arr[0]);

        var html = "";

        var sing = arr[0].split(",");

        html += '<label id="' + sing[0].split(".")[0] + '">';
        html += '<span>' + sing[1] + '</span>&nbsp;&nbsp;';
        html += '<a style="color: #0e90d2" href="' + appPath + '/popup/msg/download/' + sing[0] + '?fileName=' + sing[1] + '">下载</a>&nbsp;&nbsp;';
        html += '<a style="color: #0e90d2" onclick="delLable(\'' + sing[0].split(".")[0] + '\',\'' + imageLable + '\',\'' + arr + '\')">删除</a>';
        html += '</br>';
        html += '</label>&nbsp;&nbsp;&nbsp;';

    } else {

        // 为对应的点击图片添加值
        var lableImages = $("#" + imageLable + "Images").val();
        if (lableImages == "") {
            lableImages = fileList;
        } else {
            lableImages = lableImages + ";" + fileList;
        }
        arr = lableImages.split(";");
        $("#" + imageLable + "Images").val(lableImages);


        var html = "";
        for (var i = 0; i < arr.length; i++) {

            var sing = arr[i].split(",");

            // html += '<lable id=\'' + sing[0].split(".")[0] + '\'><span>' + sing[1] + '</span>' + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a style="color: #0e90d2" onclick="delLable(\''+sing[0].split(".")[0]+'\',\''+ imageLable +'\')" >' + '删除' + "</a></br></lable>";

            html += '<label id="' + sing[0].split(".")[0] + '">';
            html += '<span>' + sing[1] + '</span>&nbsp;&nbsp;';
            html += '<a style="color: #0e90d2" href="' + appPath + '/popup/msg/download/' + sing[0] + '?fileName=' + sing[1] + '">下载</a>&nbsp;&nbsp;';
            html += '<a style="color: #0e90d2" onclick="delLable(\'' + sing[0].split(".")[0] + '\',\'' + imageLable + '\',\'' + arr + '\')">删除</a>';
            html += '</br>';
            html += '</label>&nbsp;&nbsp;&nbsp;';

        }

    }


    $("#" + imageLable).html(html);


    layer.msg("保存成功", {icon: 1});

}


// 删除页面显示图片
function delLable(key, imageLable, fileName) {
    var result = '';
    // 获取对应lable的图片值
    var value = $("#" + imageLable + "Images").val();

    var arr = value.split(",");
    for (var i = 0; i < arr.length; i++) {
        var str = arr[i];
        var strarr = str.split(";")[0];
        var s = strarr.split(".");
        if (key == s[0]) {
            continue;
        }
        result += str + ",";
    }

    if (result != '') {
        result = result.substr(0, result.length - 1);
    }

    $("#" + imageLable + "Images").val("");
    $("#" + key).remove();

    $.ajax({
        url: appPath + '/popup/fastDelete',
        async: true,
        type: 'post',
        data: {'fileName': fileName},
        success: function (data) {
        }
    });
}

